using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.DirectX.DirectInput;
using System.Windows.Forms;

namespace TowerDefense_Dx.Core
{
    public class DxKey
    {
        protected Device _keyboard = null;
        protected Control _parent;
        private KeyboardState _state = null;
        public KeyboardState State
        {
            get { return _state; }
        }

        public DxKey(Control target)
        {
            _parent = target;
            _keyboard = new Device(SystemGuid.Keyboard);            
            _keyboard.SetCooperativeLevel(_parent, CooperativeLevelFlags.Foreground
            | CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.NoWindowsKey);
            _keyboard.SetDataFormat(DeviceDataFormat.Keyboard);
            //while (true)
            //{
            //    System.Threading.Thread.Sleep(100);
            //    Application.DoEvents();
            //    KeyboardState _state;
            //    _state = GetKBDState();
            //    if(_state != null)
            //    {
            //        if(_state[Key.Escape])
            //        {                       
            //            break;
            //        }
            //    }
            //}
        }
        
        public KeyboardState GetKeyState()
        {            
            do
            {
                Console.WriteLine("Error");
                try
                {
                    _state = this._keyboard.GetCurrentKeyboardState();
                    break;
                }
                catch (InputException)
                {
                    Application.DoEvents();
                    try
                    {
                        _keyboard.Acquire();
                    }
                    catch (InputLostException)
                    {
                        continue;
                    }
                    catch (OtherApplicationHasPriorityException)
                    {
                        continue;
                    }
                }
            } while (true);
            return _state;
        }   
    }
}
